package main

import (
	"fmt"
	"io/ioutil"
	"math/rand"
	"net/http"
	"net/http/httputil"
	"strings"

	"gopkg.in/yaml.v2"
)

type Yaml struct {
	Server struct {
		Port   string `yaml:"port"`
		Static string `yaml:"static"`
		Html   string `yaml:"html"`
		Tls    struct {
			Cert string `yaml:"cert"`
			Key  string `yaml:"key"`
		}
	}

	Proxy map[string][]string `yaml:proxy`
}

func getAddr(api []string) string {
	n := rand.Intn(len(api))
	return api[n]
}

func main() {
	conf := new(Yaml)
	yamlFile, err := ioutil.ReadFile("./config.yaml")
	if err != nil {
		panic(err)
	}
	err = yaml.Unmarshal(yamlFile, conf)
	http.HandleFunc("/api/", func(w http.ResponseWriter, r *http.Request) {
		target := r.RequestURI
		var key string
		i := strings.Index(target[1:], "/")
		key = target[1 : i+1]
		addrs := conf.Proxy[key]
		fmt.Println(addrs, key)

		if addrs == nil {
			return
		}
		last := strings.Index(target, "?")
		var curl string
		if last != -1 {
			curl = target[7+len(key) : last]
		} else {
			curl = target[7+len(key):]
		}
		proxy := httputil.ReverseProxy{Director: func(req *http.Request) {
			addr := getAddr(addrs)
			n := strings.Index(addr, ":")
			req.URL.Scheme = addr[:n]
			ip := addr[n+3:]
			n = strings.Index(ip, "/")
			path := ""
			fmt.Println(ip)
			if n != -1 {
				path = ip[n:]
				ip = ip[:n]
			}
			fmt.Println(n, ip, path)
			req.URL.Host = ip
			req.URL.Path = path + curl
		}}
		proxy.ServeHTTP(w, r)
	})
	http.Handle("/", http.FileServer(http.Dir(conf.Server.Html)))
	fmt.Println(conf.Server.Static[strings.LastIndex(conf.Server.Static, "/"):])
	http.Handle(conf.Server.Static[strings.LastIndex(conf.Server.Static, "/"):], http.FileServer(http.Dir(conf.Server.Static)))
	if conf.Server.Tls.Cert == "" || conf.Server.Tls.Key == "" {
		http.ListenAndServe(":"+conf.Server.Port, nil)
	} else {
		http.ListenAndServeTLS(":"+conf.Server.Port, conf.Server.Tls.Cert, conf.Server.Tls.Key, nil)
	}

}
